package cn.javabb.core.plugin.mail;

import cn.hutool.core.date.DateUtil;
import cn.javabb.common.utils.SpringContextUtil;
import cn.javabb.core.constant.PayConstant;
import cn.javabb.core.entity.pay.OrderDO;
import cn.javabb.core.plugin.mail.service.MailService;
import cn.javabb.core.service.pay.OrderService;
import cn.javabb.core.service.sys.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import java.util.Date;

/**
 * @Author javabb
 * @Date 2019/8/15 0015 上午 12:25
 * @Desc
 */
@Slf4j
@Component
public class MailUtil {

    @Autowired
    private MailService mailService;

    public void sendOrderMail(String orderId){
        OrderService orderService = SpringContextUtil.getBean(OrderService.class);
        TemplateEngine templateEngine =  SpringContextUtil.getBean(TemplateEngine.class);
        SysConfigService configService = SpringContextUtil.getBean(SysConfigService.class);
        String orderReceive = configService.getConfigValue(PayConstant.MAIL_ORDER_RECEIVER);
        Assert.notNull(orderReceive,"订单邮件接收邮箱设置为空");
        OrderDO order = orderService.getOrderById(orderId);
        Assert.notNull(order,"获取订单错误");
        Context context = new Context();
        // 新建临时变量
        context.setVariable("order", order);
        context.setVariable("currentDate", DateUtil.format(new Date(),"yyyy-MM-dd hh:mm:ss"));
        String emailTemplate = templateEngine.process("ftl/email/orderEmail", context);
        try {
            mailService.sendHtmlMail(orderReceive, "Javabb论坛订单服务", emailTemplate);
        } catch (MessagingException e) {
            log.error("邮件发送失败",e.getMessage());
        }

    }
}
